package service

import (
	"database/sql"
	"github.com/gogf/gf/container/garray"
	"github.com/gogf/gf/container/gvar"
	"github.com/gogf/gf/util/gconv"
	"web_api_gogf/app/dao"
	"web_api_gogf/app/model"
)

// SysPermission 系统权限服务类
var SysPermission = SysPermissionService{}

type SysPermissionService struct {
}

// GetAll 获取所有权限列表
func (s *SysPermissionService) GetAll() ([]model.SysPermissions, error) {
	permissionList := ([]model.SysPermissions)(nil)
	err := dao.SysPermissions.Scan(&permissionList)
	if err != nil {
		return nil, err
	}
	return permissionList, nil
}

// GetPermList 获取权限列表
func (s *SysPermissionService) GetPermList(searchParams *model.SysPermisssionGetListReq) ([]*model.SysPermissions, error) {
	permList := ([]*model.SysPermissions)(nil)
	modelObj := dao.SysPermissions.Safe()
	if searchParams.Name != "" {
		modelObj = modelObj.WhereLike(dao.SysPermissions.Columns.Name, "%"+searchParams.Name+"%")
	}
	if searchParams.DisplayName != "" {
		modelObj = modelObj.WhereLike(dao.SysPermissions.Columns.DisplayName, "%"+searchParams.DisplayName+"%")
	}
	if err := modelObj.Order(dao.SysPermissions.Columns.OrderNum + " ASC," + dao.SysPermissions.Columns.PermId + " asc").Scan(&permList); err != nil {
		return nil, err
	}
	return permList, nil
}

// GetPermissionIdsByRoleIds 通过角色ID列表获取权限列表
func (s *SysPermissionService) GetPermissionIdsByRoleIds(roleIds []uint) (*garray.IntArray, error) {
	var permissionIds []*gvar.Var
	permissionIds, err := dao.SysPermissionRoles.WhereIn(dao.SysPermissionRoles.Columns.RoleId, roleIds).Array("perm_id")
	if err != nil {
		return nil, err
	}
	ids := garray.NewIntArrayFrom(gconv.SliceInt(permissionIds), false).Unique()
	return ids, nil
}

// BuildTree 构建树结构数据,(由于需要保留菜单结构数据，因此每一次树结构菜单都需要在对应的service中实现，使用公共的树方法无法还原原始菜单数据)
func (s *SysPermissionService) BuildTree(resources []model.SysPermissionTree) []*model.SysPermissionTree {
	//定义根树，既id=0的根节点，我用的时候并不存在于数据库
	var rootResource = model.SysPermissionTree{}
	//创建一个map，把父级相同的地址归纳起来
	DataMap := make(map[uint][]*model.SysPermissionTree, len(resources))
	//寻找对应的父级，添加子节点集合
	for key := range resources {
		pid := resources[key].ParentId
		DataMap[pid] = append(DataMap[pid], &resources[key])
	}
	for key := range resources {
		if resources[key].ParentId == 0 {
			rootResource.Children = append(rootResource.Children, &resources[key])
		}
		resources[key].Children = DataMap[resources[key].PermId]
	}
	// 添加完成，既建立树形关系完成
	return rootResource.Children
}

// SavePerm 保存权限
func (s *SysPermissionService) SavePerm(permData *model.SysPermissionSaveReq) (sql.Result, error) {
	result, err := dao.SysPermissions.Data(permData).Save()
	if err != nil {
		return nil, err
	}
	return result, nil
}

// DelPerm 删除权限
func (s *SysPermissionService) DelPerm(permIds []uint) (sql.Result, error) {
	result, err := dao.SysPermissions.WhereIn("perm_id", permIds).Delete()
	if err != nil {
		return nil, err
	}
	return result, err
}
